package com.cli.apisdk.checkpoint.service;

import cn.hutool.core.collection.CollUtil;
import com.cli.apisdk.checkpoint.mgmtapi.SessionManagement;
import com.cli.apisdk.checkpoint.model.DeviceMetaData;
import com.cli.apisdk.checkpoint.model.LoginRequest;
import com.cli.apisdk.constant.TypeConsts;
import com.cli.apisdk.constant.VendorConsts;
import com.cli.apisdk.model.ActionType;
import com.cli.apisdk.model.RequestTarget;
import com.cli.apisdk.model.ResourceType;
import com.cli.apisdk.spi.GenerateUrlService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * <p>
 *     职责：
 *     - 生成请求URL
 *     - 发送API请求
 *     - 请求设备元数据信息[厂商、型号、版本、IP、端口]
 * </p>
 * @author: xiongmin
 * @since create by 2022/7/22 16:18
 */
@Service
public class SessionManagementService {

    @Autowired
    private SessionManagement sessionManagement;


    public String login() {
        DeviceMetaData deviceMetaData = DeviceMetaData.builder()
                .vendor(VendorConsts.CHECK_POINT)
                .type(TypeConsts.MANAGEMENT_SERVER)
                .version("v1.6")
                .mgmtIp("192.168.60.80")
                .port(443)
                .build();

        RequestTarget requestTarget = RequestTarget.builder()
                .actionType(ActionType.SESSION)
                .resourceType(ResourceType.SESSION_LOGIN)
                .build();

        LoginRequest loginRequest = LoginRequest.builder()
                .user("admin")
                .password("r00tme")
                .build();

        List<String> sessionUrls = generateUrls(deviceMetaData, requestTarget);

        if (CollUtil.isEmpty(sessionUrls)) {
            return null;
        }

        return sessionManagement.login(sessionUrls.get(0), loginRequest);
    }

    private List<String> generateUrls(DeviceMetaData deviceMetaData, RequestTarget requestTarget) {
        ServiceLoader<GenerateUrlService> urlServices = ServiceLoader.load(GenerateUrlService.class);
        for (GenerateUrlService urlService : urlServices) {
            if (!urlService.getVendor().equalsIgnoreCase(deviceMetaData.getVendor())) {
                continue;
            }
            if (StringUtils.isNotBlank(urlService.getType()) && !urlService.getType().equalsIgnoreCase(deviceMetaData.getType())) {
                continue;
            }
            return urlService.generateUrls(deviceMetaData, requestTarget.getResourceType());
        }
        return CollUtil.newArrayList();
    }

}
